<template>
  <div class="search-form">
    <a-form :layout="formState.layout" :model="formState" v-bind="formItemLayout">
      <a-row :wrap="true" :model="formState" :gutter="[8, 8]">
        <a-col v-bind="media1">
          <a-form-item>
            <a-select show-search placeholder="选择能源类型" v-model:value="formState.energyType" :options="energyType"
              @change="energyTypeChange"
              :filter-option="(input, option) => option.label.toLowerCase().includes(input.toLowerCase())"></a-select>
          </a-form-item>
        </a-col>
        <a-col v-bind="media1">
          <a-form-item>
            <a-select show-search placeholder="选择科室" v-model:value="formState.depart" :options="depart"
              @change="departChange"
              :filter-option="(input, option) => option.label.toLowerCase().includes(input.toLowerCase())"></a-select>
          </a-form-item>
        </a-col>
        <!-- <a-col v-bind="media2">
          <a-form-item>
            <a-select show-search :maxTagCount="2" placeholder="选择楼层"
              v-model:value="formState.productionLine" :options="productionLine" @change="productLineChange"
              :filter-option="(input, option) => option.label.toLowerCase().includes(input.toLowerCase())"></a-select>
          </a-form-item>
        </a-col> -->
        <a-col v-bind="media1">
          <a-form-item>
            <a-select show-search :maxTagCount="2" placeholder="选择工艺描述" v-model:value="formState.device"
              :options="device" @change="deviceChange"
              :filter-option="(input, option) => option.label.toLowerCase().includes(input.toLowerCase())" allowClear></a-select>
          </a-form-item>
        </a-col>
        <a-col v-bind="media2">
          <a-form-item>
            <a-select show-search :maxTagCount="3" zs placeholder="选择产线" mode="multiple" v-model:value="formState.unit"
              :options="unit"
              allowClear
              :filter-option="(input, option) => option.label.toLowerCase().includes(input.toLowerCase())"></a-select>
          </a-form-item>
        </a-col>
        <a-col :flex="1">
          <div class="form-btn">
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button style="margin: 0 8px" @click="handleReset">重置</a-button>
          </div>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, reactive, defineEmits, onMounted } from 'vue';
import { getDictListByCode } from '@/api/sys/dict';
import { getByParentByDict, getByParentByDictAndDataTypeId } from '@/api/power/electricity/electricity';
import { getClassifyByPatent } from '@/api/collection/classify';
import { getByParents } from '@/api/workmanship';
import { message } from 'ant-design-vue';

const emit = defineEmits(['search', 'reset']);

const media1 = {
  xs: 8,
  sm: 6,
  md: 6,
  lg: 4,
  xl: 3
};

const media2 = {
  xs: 16,
  sm: 16,
  md: 12,
  lg: 10,
  xl: 8
};

const codes = {
  array: ['technology', 'ARRAY'],
  cell: ['technology', 'CELL'],
  cf: ['technology', 'CF']
};

const props = defineProps<{
  type: any;
}>();

const energyType = ref([]);
const depart = ref([]);
const productionLine = ref([]);
const device = ref([]);
const unit = ref([]);

const formState = reactive({
  energyType: null,
  depart: null,
  productionLine: [],
  device: null,
  unit: []
});

// 标记是否为首次加载
const isFirstLoad = ref(true);

const isNotEmptyArray = (array) => {
  return !array || !array.length;
};

const handleSearch = () => {
  console.log(9999999999)
  if (!formState.energyType) {
    message.error('请选择能源类型');
    return;
  }

  if (!formState.depart) {
    message.error('请选择科室');
    return;
  }

  if (formState.device && isNotEmptyArray(formState.unit)) {
    message.error('请选择产线');
    return;
  }

  // if (isNotEmptyArray(formState.device)) {
  //   message.error('请选择设备');
  //   return;
  // }

  emit('search', { ...formState });
};

const handleReset = () => {
  formState.energyType = null;
  formState.depart = null;
  formState.productionLine = [];
  formState.device = null;
  formState.unit = [];
  emit('reset');
  // 重置时恢复首次加载状态
  isFirstLoad.value = true;
};

const getTypeList = async () => {
  try {
    const res = await getDictListByCode('process_energy_consumption_and_energy_type');
    const filteredTypes = [];

    res.forEach(item => {
      // if (['电', '水', '气'].includes(item.itemName)) {
        filteredTypes.push({ label: item.itemName, value: item.itemCode });

        // 只有首次加载时设置默认值
        // if (isFirstLoad.value) {
        //   formState.energyType = item.itemCode;
        // }
      // }
    });

    energyType.value = filteredTypes;
    if (isFirstLoad.value) {
      formState.energyType = filteredTypes[0].value;
    }
    // 如果没有找到"电"选项，给出提示
    if (isFirstLoad.value && !formState.energyType) {
      message.warning('未找到能源类型"电"，请检查数据配置');
    }
  } catch (error) {
    console.error('获取能源类型失败', error);
    message.error('获取能源类型失败');
  }
};
let dictStorge:any = {}
const getClassifyData = async () => {
  try {
    const config = codes[props.type];
    let res 
    if (dictStorge[formState.energyType]) {
      res = dictStorge[formState.energyType]
    } else {
      res = await getByParentByDictAndDataTypeId({
        dictCode: config[0],
        itemName: config[1],
        dataTypeId: formState.energyType
      });
      dictStorge[formState.energyType] = res
    }
    if (res && res.length > 0) {
      // 转换为Select组件所需的格式并保留sort字段
      depart.value = res.map(item => ({
        label: item.classifyName,
        value: item.classifyId,
        sort: item.sort,
        children: item.children
      }));

      // 只有首次加载时自动选择sort=1的数据
      if (isFirstLoad.value) {
        const defaultOption = res.find(item => item.sort === 1);
        if (defaultOption) {
          formState.depart = defaultOption.classifyId;

          // 触发下级联动
          getDevice(formState.depart);
        }
      }
    } else {
      depart.value = [];
      formState.depart = null;
      message.info('没有找到相关科室数据');
    }
  } catch (error) {
    console.error('获取科室数据失败', error);
    message.error('获取科室数据失败');
  }
};
const energyTypeChange = () => {
  formState.depart = null
  formState.device = null
  formState.productionLine = null
  formState.unit = []
  isFirstLoad.value = true;
  getClassifyData()
}
const getProductLine = async (classifyId) => {
   if (!classifyId) return;
  productionLine.value = depart.value.find(item => item.value === classifyId)?.children.map(item => ({
    label: item.classifyName,
    value: item.classifyId,
    sort: item.sort,
    children: item.children
  })).sort((a, b) => a.sort - b.sort)
   // 只有首次加载时自动选择sort=1的数据
  if (isFirstLoad.value) {
    const defaultOption = productionLine.value[0];
    if (defaultOption) {
      formState.productionLine = defaultOption.value;

      // 触发下级联动
      getDevice(formState.productionLine);
    }
  }
  return
  try {
    const res = await getClassifyByPatent({
      parentClassifyId: classifyId
    });

    if (res && res.length > 0) {
      // 转换为Select组件所需的格式并保留sort字段
      productionLine.value = res.map(item => ({
        label: item.classifyName,
        value: item.classifyId,
        sort: item.sort
      }));

      // 只有首次加载时自动选择sort=1的数据
      if (isFirstLoad.value) {
        const defaultOption = res.find(item => item.sort === 1);
        if (defaultOption) {
          formState.productionLine = [defaultOption.classifyId];

          // 触发下级联动
          getDevice(formState.productionLine);
        }
      }
    } else {
      productionLine.value = [];
      formState.productionLine = [];
      message.info('没有找到相关产线数据');
    }
  } catch (error) {
    console.error('获取产线数据失败', error);
    message.error('获取产线数据失败');
  }
};

const getDevice = async (classifyIds) => {
  if (!classifyIds) return;
  device.value = depart.value.find(item => item.value === classifyIds)?.children.map(item => ({
    label: item.classifyName,
    value: item.classifyId,
    sort: item.sort,
    children: item.children
  })).sort((a, b) => a.sort - b.sort)
  // 只有首次加载时自动选择sort=1的数据
  if (isFirstLoad.value) {
    const defaultOption = device.value[0];
    if (defaultOption) {
      formState.device = defaultOption.value;

      // 触发下级联动
      getUnit(formState.device);
    }
  }
  return
  try {
    const res = await getByParents({
      classifyIds: classifyIds // 直接传递数组
    });

    if (res && res.length > 0) {
      // 转换为Select组件所需的格式并保留sort字段
      device.value = res.map(item => ({
        label: item.classifyName,
        value: item.classifyId,
        sort: item.sort
      }));

      // 只有首次加载时自动选择sort=1的数据
      if (isFirstLoad.value) {
        const defaultOption = res.find(item => item.sort === 1);
        if (defaultOption) {
          formState.device = [defaultOption.classifyId];

          // 触发下级联动
          getUnit(formState.device);
        }
      }
    } else {
      device.value = [];
      formState.device = [];
      message.info('没有找到相关设备数据');
    }
  } catch (error) {
    console.error('获取设备数据失败', error);
    message.error('获取设备数据失败');
  }
};

const getUnit = async (classifyIds) => {

  if (!classifyIds) return;
  unit.value = device.value.find(item => item.value === classifyIds)?.children.map(item => ({
    label: item.classifyName,
    value: item.classifyId,
    sort: item.sort,
  })).sort((a, b) => a.sort - b.sort)
  // 只有首次加载时自动选择sort=1的数据
  if (isFirstLoad.value) {
    const defaultOption = unit.value[0];
    if (defaultOption) {
      formState.unit = [defaultOption.value];
    }
    handleSearch();
    // 搜索后将首次加载标记设为false
    isFirstLoad.value = false;
  }
  return
  try {
    const res = await getByParents({
      classifyIds: classifyIds // 直接传递数组
    });

    if (res && res.length > 0) {
      // 转换为Select组件所需的格式并保留sort字段
      unit.value = res.map(item => ({
        label: item.classifyName,
        value: item.classifyId,
        sort: item.sort
      }));

      // 只有首次加载时自动选择sort=1的数据
      if (isFirstLoad.value) {
        const defaultOption = res.find(item => item.sort === 1);
        if (defaultOption) {
          formState.unit = [defaultOption.classifyId];
          
          // 只有首次加载完成后才自动搜索
          if (isFirstLoad.value) {
            handleSearch();
            // 搜索后将首次加载标记设为false
            isFirstLoad.value = false;
          }
        }
      }
    } else {
      unit.value = [];
      formState.unit = [];
      message.info('没有找到相关单元数据');
    }
  } catch (error) {
    console.error('获取单元数据失败', error);
    message.error('获取单元数据失败');
  }
};

const departChange = (value) => {
  if (!value) {
    // 清空科室时，重置后续所有选项
    // formState.productionLine = [];
    formState.device = null;
    formState.unit = [];
    // productionLine.value = [];
    device.value = [];
    unit.value = [];
  } else {
    // 选择楼层时，重置后续选项并加载产线数据
    // formState.productionLine = [];
    formState.device = null;
    formState.unit = [];
    // productionLine.value = [];
    device.value = [];
    unit.value = [];
    getDevice(value);
  }
};

const productLineChange = (selectedValues) => {
  if (isNotEmptyArray(selectedValues)) {
    // 清空产线时，重置后续所有选项
    formState.device = [];
    formState.unit = [];
    device.value = [];
    unit.value = [];
  } else {
    // 选择产线时，重置后续选项并加载设备数据
    formState.device = [];
    formState.unit = [];
    device.value = [];
    unit.value = [];
    getDevice(selectedValues);
  }
};

const deviceChange = (selectedValues) => {
  if (isNotEmptyArray(selectedValues)) {
    // 清空设备时，重置后续所有选项
    formState.unit = [];
    unit.value = [];
  } else {
    // 选择设备时，重置后续选项并加载单元数据
    formState.unit = [];
    unit.value = [];
    getUnit(selectedValues);
  }
};

onMounted(async () => {
  await getTypeList();
  await getClassifyData();
});
</script>

<style lang="less" scoped>
.search-form {
  box-sizing: border-box;
  margin-bottom: 8px;
  padding: 8px;
  background: #FFF;
  box-shadow: 1px 1px 4px 0 rgb(0 0 0 / 15%);

  .form-btn {
    display: flex;
    justify-content: flex-end;
  }

  .ant-form-item {
    margin-bottom: 0 !important;
  }
}
</style>